package com.authine.cloudpivot.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.util.OssUtil;
import com.authine.cloudpivot.util.Result;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/api/workLog")
@Slf4j
public class interviewWorkLogController extends BaseController {


    @Autowired
    private BizObjectFacade bizObjectFacade;

    @Autowired
    private JPANativeQuery jpaNativeQuery;

    @PersistenceContext
    private EntityManager entityManager;

    @PostMapping("/updatePetitionresident")
    @Transactional
    public Result updatePetitionresident(@RequestBody JSONObject object){
        if (StringUtils.isBlank(object.getString("id"))){
            return Result.fail("参数不能为空");
        }
        String id = object.getString("id");
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("interviewWorkLog", id);
        if (Objects.isNull(bizObject)){
            return Result.fail("未找到模型");
        }
        //维稳人员id
        String createrId = bizObject.getCreater().getId();
        String xfdxSql = String.format("SELECT * FROM `iknn4_interviewresident` where parentId = '%s'",id);
        List<Map<String,Object>> list = jpaNativeQuery.getList(xfdxSql, null, null);
        if (CollectionUtils.isEmpty(list)){
            return Result.ok();
        }
        //走访对象子表
        for (Map<String,Object> map : list){
            String residentId = (String) map.get("relevanceResident");
            String xfsql = String.format("SELECT * FROM `iknn4_petitionresident`  where relevanceResident = '%s'",residentId);
            List<Map<String,Object>> xfryList = jpaNativeQuery.getList(xfsql, null, null);
            if (CollectionUtils.isNotEmpty(xfryList)){
                Map<String, Object> objectMap = xfryList.get(0);
                //信访表id
                String xfObjId =(String) objectMap.get("id");
                String isExistenceSql  = String.format("SELECT xf.id FROM `iknn4_petitionresident` xf left join  iknn4_maintainstabilitys xfzb on xf.id = xfzb.parentId where xf.id = '%s' and  xfzb.maintainstability = '%s'",xfObjId,createrId);
                List<Map<String,Object>> isExistence = jpaNativeQuery.getList(isExistenceSql, null, null);
                if (CollectionUtils.isNotEmpty(isExistence)){
                    String querySql = String.format("select * from iknn4_worklogs where relevanceWorkLog = '%s'",id);
                    List list2 = jpaNativeQuery.getList(querySql, null, null);
                    if(CollectionUtils.isNotEmpty(list2)){
                        return Result.fail("信访表已填写");
                    }
                    String uuid = UUID.fastUUID().toString();
                    String workRecord =(String) bizObject.get("workRecord");
                    if (StringUtils.isBlank(workRecord)){
                        workRecord = "";
                    }
                    String insertSql = String.format("insert into iknn4_worklogs (id,interviewTime,modifiedTime,modifier,parentId,project,recorder,relevanceWorkLog,theme,workRecord) VALUES ('%s','%s',NOW(),'%s','%s','%s','%s','%s','%s','%s')",uuid ,bizObject.get("interviewTime"),createrId,xfObjId,bizObject.get("project"),createrId,id,bizObject.get("theme"),workRecord);
                    Query nativeQuery = entityManager.createNativeQuery(insertSql);
                    nativeQuery.executeUpdate();
                    //操作附件
                    String fileSql = String.format("select * from h_biz_attachment where bizObjectId = '%s' and schemaCode = 'interviewWorkLog'",id);
                    List<Map<String,Object>> list1 = jpaNativeQuery.getList(fileSql, null, null);
                    if (CollectionUtils.isNotEmpty(list1)){
                        for (Map<String,Object> files : list1){
                            String refId =(String) files.get("refId");
                            String newFileId = OssUtil.copyFile(refId);
                            String CopyFileSql = String.format("INSERT INTO `cloudpivot`.`h_biz_attachment` (`id`, `bizObjectId`, `bizPropertyCode`, `createdTime`, `creater`, `fileExtension`, `fileSize`, `base64ImageStr`, `mimeType`, `name`, `parentBizObjectId` , `refId`, `schemaCode`) VALUES ('%s', '%s', 'workImgs', NOW(), '%s', '%s', %s, NULL, '%s', '%s','%s', '%s', 'workLogs')", UUID.fastUUID().toString(), uuid, createrId, files.get("fileExtension"), files.get("fileSize"), files.get("mimeType"), files.get("name"),xfObjId ,newFileId);
                            Query nativeQuery2 = entityManager.createNativeQuery(CopyFileSql);
                            nativeQuery2.executeUpdate();
                        }
                    }
                }
            }
        }
        return Result.ok();
    }
}
